package com.chanceit.ssss.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxParams;

import opensource.jpinyin.PinyinHelper;

import org.gl.GlobalVariable;
import org.gl.customview.listview.PinnedSectionListView;
import org.gl.ui.manger.AjaxCallBackProxy;
import org.gl.utils.Tip;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.chanceit.ssss.adapters.SimpleCustomAdapter;
import com.chanceit.ssss.adapters.SimpleSectionListViewAdapter;
import com.chanceit.ssss.dialog.SimplePopuWindow;
import com.nostra13.universalimageloader.core.ImageLoader;

public class CarTypePickerActivity extends BaseFragmentActivity {
	public static final String key_PickedCarID = "carId";
	public static final String key_CarBrand = "brand";
	public static final String key_PickName = "name";

	private void setPickResult(int id,String name) {
		Intent i = getIntent();
		i.putExtra(key_PickedCarID, id);
		i.putExtra(key_PickName, name);
		setResult(RESULT_OK, i);
	}

	/**
	 * 车型数据结构 品牌->车型 ->车系 [{"brand",data}] key data
	 */
	JSONArray json_cartypes = new JSONArray();

	final String key_dataList = "dataList";
	String cities[];
	// Countries names
	private String countries[] = new String[] { "USA", "Canada", "Ukraine",
			"France" };;
	String brand;
	private View loading;
	ListView city;
	ListView country;
//	private Spinner mSpinner;
	ImageView iv_title_bar_right;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_car_type_picker);
		loading = findViewById(R.id.loading);
		brand = getIntent().getStringExtra(key_CarBrand);
		Tip.show("默认品牌" + brand);
		// initBrandData(); FIXME
		login();
		initCountryWheel();
		initCityWheel();
	}

	private void initCityWheel() {
		city = (ListView) findViewById(R.id.city);
		// city.setAllItemsVisible(true);
		// city.setVisibleItems(10);
		// city.setViewAdapter(new CityAdapter(this));
		// city.addChangingListener(new OnWheelChangedListener() {
		// public void onChanged(AbstractWheel wheel, int oldValue,
		// int newValue) {
		// // if (!scrolling) {
		// // mActiveCities[mActiveCountry] = newValue;
		// // }
		// }
		// });
		city.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// setPickResult(position);
				((CountryAdapter) parent.getAdapter()).setSelect(position);
			}
		});
	}

	private void initCountryWheel() {
		country = (ListView) findViewById(R.id.country);
		// country.setVisibleItems(10);
		// country.setViewAdapter(new CountryAdapter(this));
		// country.setAllItemsVisible(true);
		// country.addChangingListener(new OnWheelChangedListener() {
		// public void onChanged(AbstractWheel wheel, int oldValue,
		// int newValue) {
		// if (!scrolling) {
		// // updateCities(city, cities, newValue);
		// try {
		// updateCities(newValue);
		// lg.i(TAG, "country" + "onChanged");
		// } catch (JSONException e) {
		// e.printStackTrace();
		// }
		// }
		//
		// }
		// });
		//
		// country.addScrollingListener(new OnWheelScrollListener() {
		// public void onScrollingStarted(AbstractWheel wheel) {
		// scrolling = true;
		// }
		//
		// public void onScrollingFinished(AbstractWheel wheel) {
		// scrolling = false;
		// // updateCities(city, cities, country.getCurrentItem());
		// // lg.i(TAG, "country"+"onScrollingFinished");
		// }
		// });
		country.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				((CountryAdapter) parent.getAdapter()).setSelect(position);
				country.setSelection(position);
				try {
					updateCities(position);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void login() {
		AjaxParams par = new AjaxParams();
		par.put("account", "sys");
		par.put("password", "123456");
		par.put("mobile", "mobile");
		ds.getData("account_login", null, par, new AjaxCallBackProxy<String>(
				loading) {
			@Override
			public void onSuccess(String t) {
				initBrandData();
			}
		});
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.cartype_btn_pick:
			// System.out.println("pick:"
			// + cities[country.getCurrentItem()][city.getCurrentItem()]);
			int id = 0;
			try {
				lg.i(TAG, "" + json_cartypes);
				JSONObject temp = json_cartypes
						.getJSONObject(adapter.getSelect()).getJSONArray(key_dataList)
						.getJSONObject(
								((CountryAdapter) country.getAdapter())
										.getSelect()).getJSONArray(key_dataList)
						.getJSONObject(
								((CountryAdapter) city.getAdapter())
										.getSelect());
				id = temp.optInt("carId");
				setPickResult(id,temp.optString("brand")
						+ temp.optString("seriesName")
						+ temp.optString("carName"));
				Tip.show("选择了" + temp.optString("brand")
						+ temp.optString("seriesName")
						+ temp.optString("carName"));
				onBackPressed();
			} catch (Exception e) {
				e.printStackTrace();
				Tip.show("未选择具体车型");
			}
			break;
		case R.id.iv_title_bar_right:
			showBrandListViewPopuWindow(v);
			break;
		case R.id.rl_title_brand:
			showBrandListViewPopuWindow(v);
			break;

		default:
			break;
		}
	}

	SimplePopuWindow popupWindow_brandListView;
	private PinnedSectionListView listView_brand;

	private void showBrandListViewPopuWindow(View view) {
		if (popupWindow_brandListView == null) {
			return;
		}
		if (!popupWindow_brandListView.isShowing()) {
			popupWindow_brandListView.showAsDropDown(view);
		} else {
			popupWindow_brandListView.dismiss();
		}
	}

	/**
	 * series_models
	 */
//	private void initBrandSpinner() {
//		if (json_cartypes == null) {
//			initBrandData();
//			return;
//		}
//		iv_title_bar_right = (ImageView) findViewById(R.id.iv_title_bar_right);
//		iv_title_bar_right.setOnClickListener(this);
//		mSpinner = (Spinner) findViewById(R.id.cartype_spinner_brand);
//		// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
//		// R.layout.spinner_item_check_text, new String[] { "通用别克", "宝马" });
//		// 设置下拉列表的风格
//		adapter.setDropDownViewResource(R.layout.list_item_brand);
//		// 将adapter 添加到spinner中
//		mSpinner.setAdapter(adapter);
//		// 添加事件Spinner事件监听
//		mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
//
//			public void onItemSelected(AdapterView<?> arg0, View arg1,
//					int arg2, long arg3) {
//				getSeriesListData(arg2);
//			}
//
//			public void onNothingSelected(AdapterView<?> arg0) {
//			}
//		});
//
//		// 设置mSpinner默认的品牌
//		int defaultSecletindex = 0;
//		if (TextUtils.isEmpty(brand)) {
//			brand = (String) mSpinner.getPrompt();
//			mSpinner.setSelection(defaultSecletindex, true);
//		} else {
//			for (int i = 0; i < json_cartypes.length(); i++) {
//				JSONObject jo = json_cartypes.optJSONObject(i);
//				if (brand.equalsIgnoreCase(jo.optString("brand"))) {
//					defaultSecletindex = i;
//				}
//			}
//			mSpinner.setSelection(defaultSecletindex, true);
//		}
//		initSeriesList();
//	}

	private void initSeriesList() {
		getSeriesListData(adapter.getSelect());
	}

	/**
	 * 获取车系列表数据
	 * 
	 * @param selectedItemPosition
	 */
	private void getSeriesListData(int selectedItemPosition) {
		final int currentindex = selectedItemPosition;
		final JSONObject jo = json_cartypes.optJSONObject(currentindex);
		JSONArray SeriseArray;
		try {
			SeriseArray = jo.optJSONArray(key_dataList);
		} catch (Exception e1) {
			SeriseArray = null;
			e1.printStackTrace();
		}
		if (SeriseArray == null || SeriseArray.length() <= 0) {
			AjaxParams par = new AjaxParams();
			par.put("brand", jo.optString("brand"));
			ds.getData("series_list", null, par, new AjaxCallBackProxy<String>(
					loading) {
				@Override
				public void onStart() {
					super.onStart();
					country.setAdapter(new CountryAdapter(
							CarTypePickerActivity.this, new String[0],
							new String[0]));
				}

				@Override
				public void onSuccess(String t) {
					super.onSuccess(t);
					lg.i(TAG, "getSeriesListData:" + t);
					String mesage = "";
					try {
						JSONArray result = new JSONArray(t);
						// {"seriesId":3,"brand":"福特","brandImage":"bbb.jpg","seriesName":"福克斯
						jo.put(key_dataList, result);
						int count = result.length();
						countries = new String[count];
						String[] countries_depot = new String[count];
						for (int i = 0; i < count; i++) {
							JSONObject temp = result.optJSONObject(i);
							countries[i] = temp.optString("seriesName");
							countries_depot[i] = temp.optString("depot");
						}
						initCountryWheel();
						country.setAdapter(new CountryAdapter(
								CarTypePickerActivity.this, countries,
								countries_depot));
						initCityWheel();
						updateCities(0);
					} catch (JSONException e) {
						e.printStackTrace();
						mesage = e.getMessage();
						loadFailed(mesage);
					}
				}
			});
		} else {
			JSONArray result = SeriseArray;
			int count = result.length();
			countries = new String[count];
			String[] countries_depot = new String[count];
			for (int i = 0; i < count; i++) {
				JSONObject temp;
				try {
					temp = result.getJSONObject(i);
					countries[i] = temp.optString("seriesName");
					countries_depot[i] = temp.optString("depot");
					country.setAdapter(new CountryAdapter(
							CarTypePickerActivity.this, countries,
							countries_depot));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			initCityWheel();
			try {
				updateCities(0);
			} catch (JSONException e) {
				e.printStackTrace();
				Tip.show("获取车型数据失败" + e.getMessage());
			}

		}
	}

	/**
	 * 针对品牌 josn中对应的KEY
	 */
	String[] keys = new String[] { "", "", "brand", "", "brandImage" };
	/**
	 * 针对车型 josn中对应的KEY
	 */
	String[] keys_carType = new String[] { "carName", "", "", "", "" };
	/**
	 * 针对品牌
	 */
	SimpleSectionListViewAdapter adapter;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();

	/**
	 * 初始化品牌列表
	 */
	private void initBrandData() {
		AjaxParams par = new AjaxParams();
		ds.getData("series_models", null, par, new AjaxCallBackProxy<String>(
				loading) {
			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				lg.i(TAG, t);
				String mesage = "";
				try {
					JSONArray result = new JSONArray(t);

					int count = result.length();
					contents.removeAll(contents);
					for (int i = 0; i < count; i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						JSONObject temp = result.getJSONObject(i);
						for (String key : keys) {
							Object o = temp.opt(key);
							if (o == null) {
								o = "";
							}
							if (key.equals("brandImage")) {
								o = GlobalVariable.URL_image + o.toString();
							}
							if (key.equals("brand")) {
								String shortName = PinyinHelper
										.getShortPinyin(o.toString());
								map.put("brandShortName", shortName);
							}
							map.put(key, o.toString());
						}
						contents.add(map);
					}

					// 添加到一级列表
					json_cartypes = result;

					if (adapter == null) {
						if (contents.size() > 0) {
							adapter = new SimpleSectionListViewAdapter(
									CarTypePickerActivity.this,
									(List<Map<String, Object>>) contents,
									R.layout.list_item_brand, keys, new int[] {
											R.id.textView1, R.id.textView2,
											R.id.textView3, R.id.textView4,
											R.id.textView5 });
//							initBrandSpinner();
							initBrandPopuWinList();
							// 设置默认的品牌
							int defaultSecletindex = 0;
							if (TextUtils.isEmpty(brand)) {
//								brand = (String) mSpinner.getPrompt();
							} else {
								for (int i = 0; i < json_cartypes.length(); i++) {
									JSONObject jo = json_cartypes.optJSONObject(i);
									if (brand.equalsIgnoreCase(jo.optString("brand"))) {
										defaultSecletindex = i;
									}
								}
							}
							adapter.setSelect(defaultSecletindex);
							setCurrentBrandView(defaultSecletindex);
							findViewById(R.id.rl_title_brand).setOnClickListener(CarTypePickerActivity.this);
							initSeriesList();
						}
					} else {
						adapter.notifyDataSetChanged();
					}

				} catch (JSONException e) {
					e.printStackTrace();
					mesage = e.getMessage();
					loadFailed(mesage);
				}
			}

			private void initBrandPopuWinList() {
				if (popupWindow_brandListView == null) {
					listView_brand = new PinnedSectionListView(getBaseContext());
					listView_brand.setAdapter(adapter);
					listView_brand.setFastScrollEnabled(true);
					listView_brand
							.setOnItemClickListener(new OnItemClickListener() {
								@Override
								public void onItemClick(AdapterView<?> parent,
										View view, int position, long id) {
									getSeriesListData(position);
									popupWindow_brandListView.dismiss();
									adapter.setSelect(position);
									setCurrentBrandView(position);
								}

							});
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
						listView_brand.setFastScrollAlwaysVisible(true);
					}
					listView_brand.setBackgroundResource(R.color.bg);
					// 自适配长、框设置
					popupWindow_brandListView = new SimplePopuWindow(
							listView_brand);
				}
			}
		});

	}

	/**
	 * 显示当前选中的品牌
	 * 
	 * @param position
	 */
	private void setCurrentBrandView(int position) {
		JSONObject jo = json_cartypes.optJSONObject(position);
		if (jo != null) {
			((TextView) findViewById(R.id.textView3)).setText(jo
					.optString("brand"));
			ImageLoader.getInstance().displayImage(
					GlobalVariable.URL_image + jo.optString("brandImage"),
					((ImageView) findViewById(R.id.textView5)));
		}

	}

	/**
	 * 获取具体车型的数组
	 * 
	 * @param index
	 *            车型数组对应的索引
	 * @throws JSONException
	 */
	private void updateCities(int index) throws JSONException {
		// 当前的车系
		final JSONObject jo = json_cartypes
				.optJSONObject(adapter.getSelect())// 获取品牌
				.getJSONArray(key_dataList).getJSONObject(index);// 获取车系
		if (jo == null) {
			lg.i(TAG, "Serrise is null");
			return;
		}
		JSONArray carInfoArray;
		try {
			carInfoArray = jo.optJSONArray(key_dataList);
		} catch (Exception e1) {
			carInfoArray = null;
			e1.printStackTrace();
		}
		if (carInfoArray == null || carInfoArray.length() <= 0) {
			AjaxParams par = new AjaxParams();
			par.put("brand", jo.optString("brand"));
			par.put("seriesId", jo.optString("seriesId"));
			par.put("seriesName", jo.optString("seriesName"));
			ds.getData("car_listAll", null, par, new AjaxCallBackProxy<String>(
					loading) {
				@Override
				public void onStart() {
					super.onStart();
					city.setAdapter(new CountryAdapter(
							CarTypePickerActivity.this, new String[0],
							new String[0]));
				}

				@Override
				public void onSuccess(String t) {
					super.onSuccess(t);
					lg.i(TAG, t);
					String mesage = "";
					try {
						JSONArray result = new JSONArray(t);
						// {"seriesId":3,"brand":"福特","brandImage":"bbb.jpg","seriesName":"福克斯
						jo.put(key_dataList, result);
						int count = result.length();
						cities = new String[count];
						for (int i = 0; i < count; i++) {
							JSONObject temp = result.optJSONObject(i);
							cities[i] = temp.optString("carName");
						}

						city.setAdapter(new CountryAdapter(
								CarTypePickerActivity.this, cities, null));
					} catch (JSONException e) {
						e.printStackTrace();
						mesage = e.getMessage();
						loadFailed(mesage);
					}
				}
			});
		} else {
			JSONArray result = carInfoArray;
			int count = result.length();
			cities = new String[count];
			for (int i = 0; i < count; i++) {
				JSONObject temp;
				try {
					temp = result.getJSONObject(i);
					cities[i] = temp.optString("carName");
					city.setAdapter(new CountryAdapter(
							CarTypePickerActivity.this, cities, null));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		}

	}

	protected LayoutInflater inflater;

	/**
	 * Adapter for countries
	 */
	private class CountryAdapter extends BaseAdapter {
		private String name[] = new String[0];
		private String images[] = new String[0];
		private String title[] = new String[0];

		protected CountryAdapter(Context context, String[] name, String[] images) {
			this.name = name;
			this.images = images;
			this.title = images;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		protected CharSequence getItemText(int index) {
			return name[index];
		}

		@Override
		public int getCount() {
			return name.length;
		}

		@Override
		public Object getItem(int position) {
			if (images != null) {
				return images[position];
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		private int select = 0;

		public void setSelect(int select) {
			this.select = select;
			notifyDataSetChanged();
		}

		public int getSelect() {
			return select;
		}

		@Override
		public View getView(int index, View convertView, ViewGroup parent) {

			View view = inflater.inflate(R.layout.country_item, null);

			TextView name = (TextView) view.findViewById(R.id.country_name);
			name.setText(getItemText(index));
			if (index == select) {
				name.setTextColor(0xffffffff);
			} else {
				name.setTextColor(0xff888888);
			}
			TextView tv = (TextView) view.findViewById(R.id.title);
			String t = null;
			if (title != null) {
				if (index <= 0) {
					t = title[index];
				} else {
					if (title[index - 1].equals(title[index])) {// 上一个与这一个字符串相等吗?
					} else {
						t = title[index];
					}
				}
			}
			if (!TextUtils.isEmpty(t)) {// 不显示分类小标题
				tv.setText(t);
				tv.setVisibility(View.VISIBLE);
			} else {
				tv.setVisibility(View.GONE);
			}
			ImageView img = (ImageView) view.findViewById(R.id.flag);
			if (index == select) {
				img.setBackgroundResource(R.drawable.wheel_cover_select);
			} else {
				img.setBackgroundColor(0x00000000);
			}
			return view;

		}
	}

}
